package com.dozen.share;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dozen.commonbase.router.ARouterLocation;
import com.dozen.commonbase.utils.EmptyCheckUtil;
import com.dozen.commonbase.utils.MyLog;
import com.dozen.commonbase.utils.RegexUtils;
import com.dozen.commonbase.utils.TimeUtil;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author: Dozen  2020/9/9
 * @description: 描述
 */
@Route(path = ARouterLocation.app_shares)
public class H5Act extends Activity {

    private WebView webView;
    private View viewShow;

    @Autowired
    UrlBean urlBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        setContentView(R.layout.act_h5_dozen);
        webView = findViewById(R.id.webView);

        viewShow = findViewById(R.id.show_black);
        findViewById(R.id.copy_now).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewShow.getVisibility() == View.VISIBLE) {
                    viewShow.setVisibility(View.GONE);
                } else {
                    viewShow.setVisibility(View.VISIBLE);
                }
            }
        });

        if (EmptyCheckUtil.isEmpty(urlBean)) {
            finish();
            return;
        }

        String web_url = urlBean.getUrl();

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(web_url);
        webView.setWebChromeClient(webChromeClient);
        webView.setDownloadListener(null);
        webView.setWebViewClient(webViewClient);

        WebSettings mWebSettings = webView.getSettings();
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);

        //使用缓存，否则localstorage等无法使用
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = this.getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setBlockNetworkImage(false);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setAppCacheEnabled(false);
        mWebSettings.setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.117 Safari/537.36");

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);
        //adwebkit 指的是类（接口）的别名 ，在我们上面的代码中也就是JavascriptInterface类 所以android和js要约定好的就是 类的别名 以及 方法名 即可调用成功。
        webView.addJavascriptInterface(new AndroidJs(), "myObj");//adwebkit

    }

    private void injectJsSample() {

        String js = "var script = document.createElement('script');";                   //常规操作
        js += "function imgIdClick(val){" +
                "       var urlShow = document.getElementsByClassName(\"" + urlBean.getSelectClass() + "\")[val];\n" +
                "       myObj.openImage(urlShow.innerText,val);" +
                "};";

        //tableContent
        //ui-table-ss
        MyLog.d("111" + js);

        webView.loadUrl("javascript:" + js);

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (isback) {
                        return;
                    }
                    try {
                        Thread.sleep(10);
                        handler.sendEmptyMessage(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (!isback) {
                webView.loadUrl("javascript: imgIdClick(" + msg.what + ")");
            }
        }
    };

    private boolean isback = false;

    private void toCopy() {

        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        ClipData primaryClip = cm.getPrimaryClip();
        MyLog.d(primaryClip.getItemAt(0).getText().toString());

    }

    /**
     * 点击查看图片
     */
    public class AndroidJs {
        @JavascriptInterface
        public void openImage(String data, int val) {
            if (!isback) {
                MyLog.d("________" + val + "________" + urlBean.getSelectId() + "________" + data);

                if (val == urlBean.getSelectId()) {

                    switch (urlBean.getType()) {
                        case ShareType.share_type_dongfancaifu:
                            saveTwo(data);
                            break;
                        default:
                            saveOne(data);
                            break;
                    }

                    if (urlBean.isShow()) {
                        isback = true;
                        setResult(RESULT_OK);
                        finish();
                    }

                }

            }
        }
    }

    private void saveOne(String data) {
        List<String> list = RegexUtils.getMatches("[\\u4e00-\\u9fa5]{0,}", data);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).length() > 3) {
                ShareBean shareBean = new ShareBean();
                shareBean.setName(list.get(i));
                shareBean.setNumber(1);
                shareBean.setTimes(TimeUtil.getCurrentDataTwo());
                MyLog.d("111111111:" + list.get(i));
                ShareConstant.addShare(shareBean);
            }
        }

    }

    private void saveTwo(String data) {
        String[] list = data.split("吧");
        for (String s : list) {
            if (s.length() > 3) {
                ShareBean shareBean = new ShareBean();
                shareBean.setName(s);
                shareBean.setNumber(1);
                shareBean.setTimes(TimeUtil.getCurrentDataTwo());
                MyLog.d("111111111:" + s);
                ShareConstant.addShare(shareBean);
            }
        }
    }

    WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            titleView.setTitle(title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
        //=========HTML5定位==========================================================

        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(view);
            resultMsg.sendToTarget();
            return true;
        }
    };

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            injectJsSample();
        }
    };
}
